<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;

use app\Common;
use app\controller\Token;
use app\model\UserModel;
use app\model\DeptModel;


class Acc{
    //常用数据表内容 及常用字典
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";
    var $dept=[];
    var $users =[];
    var $payment =[];

    var $status=array('1'=>'待审核','2'=>'已审核','4'=>'已取消');
    var $acc_type=array(1=>'普通充值',2=>'其他收款',3=>'红包',5=>'推广费',6=>'其他付款',7=>'提现');

    public function __construct(){

        $um=new UserModel();
        $this->users = $um->getAll();

        $dm=new DeptModel();
        $this->dept = $dm->getAll();

        $list = Db::table('sys')->where('id',1)->value('payment');
        $arr = explode(",",$list);
        foreach($arr as $payment){
            $aa = explode(":",$payment);
            $this->payment[$aa[0]]=$aa[1];
        }

        $users=Db::table('user')->select()->toArray();
        $this->users=[];
        foreach($users as $user){
            $this->users[$user['id']] = $user;
        }
    }

    public function getOne(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/index/target/admin");  
        
        $all=Request::param();

        return json(['code'=>0,'msg'=>'没找到任何信息！']);

    }

     public function index(){

        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/index/target/admin");

        $all=Request::param();

        return View::fetch();
    }  


    //充值，后台操作
    public function acc_input($type='',$value=0,$all=[]){
        $uid=Session::get('logonid');
        $all = Request::param();

        if(empty($uid) && empty($all['token'])) return '非法操作,系统已记录来源!';

        //app端提交token
        if(!empty($all['token'])){
            $token =new token();
            $res = $token->check_token($all['token']);
            if($res['code']==0) return json($res);

            $all['cid'] = $res['customer']['id'];

        }else{
            //后台录入用session判断
            if(empty($uid)) return header("location:/index.php/login/index/target/admin");
        }

        if(!empty($all['money'])){

            if(empty($all['cid'])) return json(['code'=>0,'msg'=>'找不到客户 1!']);
            $cid = $all['cid'];

            $user = Db::table('user')->find($cid);
            if(!$user) return json(['code'=>0,'msg'=>'找不到客户 2!']);

            if(!is_numeric($all['money'])){
                return json(['code'=>0,'msg'=>'金额错误!']);
            }
            if(empty($all['type'])) {
                return json(['code'=>0,'msg'=>'类型错误!']);
            }
            if(empty($all['payment'])) {
                return json(['code'=>0,'msg'=>'支付方式错误!']);
            }            
            
            //退款或提现(6,7)
            if($all['type']>5){
                if($all['money']<10) return json(['code'=>0,'msg'=>'金额低于10元就别提现了吧，不然财务人员很累的哦!']);
                $all['money'] = -$all['money'];

                $acc_list = Db::query('select * from acc_log where customer_id=? and type=7 and status=1',[$cid]);
                if(count($acc_list)) return json(['code'=>0,'msg'=>'提现或退款已在处理中，请耐心等待财务审核打款！']);                
            }

            $acc_log=array(
                'type'=>$all['type'],
                'customer_id'=>$cid,
                'dept_id'=>1,
                'money'=>$all['money'],
                'memo'=>!empty($all['memo'])?$all['memo']:'',
                'payment'=>$all['payment'],
                'creater'=>!empty($all['token'])?2:$uid,
                'create_time'=>date('Y-m-d H:i:s'),
                'status'=>1
            );

            $nid =Db::table('acc_log')->insertGetId($acc_log);

            if(!empty($all['token']) && $nid){
                return json(['code'=>1,'msg'=>'提现已申请，待财务审核打款！']);
            }else{
                $row = Db::table('acc_log')->find($nid);
                $row['customer_id_name'] = $this->users[$row['customer_id']]['name'];
                $row['type_name'] =$this->acc_type[$row['type']];
                $row['status_name'] =$this->status[$row['status']];
                $row['creater_name'] =$this->users[$row['creater']]['name'];
                $row['payment_name'] =$this->payment[$row['payment']];
                $row['money'] =number_format($row['money'],2);

                return json_encode(['code'=>1,'data'=>$row,'msg'=>'操作成功,本次'.$row['type_name'].'金额:'.$all['money']]);
            }
        }


        View::assign(['acc_type'=>$this->acc_type,'payment'=>$this->payment,'type'=>$type,'value'=>$value,'memo'=>$all['memo']]);
        return View::fetch('charge_by_admin');
    }


    //充值提现审核
    public function charge_check(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/login");
        $all=Request::param();

        if(!empty($all['id'])){

            $id = $all['id'];
            $acc = Db::table('acc_log')->find($id);   

            if(!$acc){
                return json_encode(['code'=>0,'msg'=>'错误！!']);
            }
            if(!$acc['status']==2){
                return json_encode(['code'=>0,'msg'=>'已审核 !!']);
            }

            $user = $this->users[$acc['customer_id']];

            //提现余额检测
            if($acc['type']==7){
                $money = $user['money'];
                if($money<abs($acc['money'])){
                    return json_encode(['code'=>0,'msg'=>'余额【'.$money."】不足,提现【".abs($acc['money'])."】失败！"]);
                }
            }

            $money_after = $user['money'] + $acc['money'];
            
            $acc['status'] = $all['status'];
            $acc['check_by'] = $uid;
            $acc['check_time']=date('Y-m-d H:i:s');
            $acc['money_before'] = $user['money'];
            $acc['money_after'] = $money_after;

            $money_v=Common::scode()($money_after.$user['create_time']);//金额校验值

            $res = Db::table('acc_log')->update($acc); 
            $res= Db::execute('update user set money=?,money_v=? where id=?',[$money_after,$money_v,$acc['customer_id']]);

            if($res){
                return json_encode(['code'=>1,'msg'=>$all['status']==2 ?'审核完成！':'款项已取消！']);
            }
            return json_encode(['code'=>0,'msg'=>'审核失败，请联系技术人员！']);

        }

        $name = (!empty($all['name']))?$all['name']:'';
        $mobile = (!empty($all['mobile']))?$all['mobile']:'';

        $acc_list = Db::table('acc_log')->where('status','1')->order('create_time','desc')->paginate()->toArray();

        foreach($acc_list['data'] as &$acc){
            $acc['customer_id_name'] = $this->users[$acc['customer_id']]['name'];
            $acc['type_name'] = $this->acc_type[$acc['type']];
            $acc['payment_name'] = $this->payment[$acc['payment']];
            $acc['status_name'] = $this->status[$acc['status']];
            $acc['creater_name'] = $this->users[$acc['creater']]['name'];

        }

        View::assign(['list'=>$acc_list,'name'=>$name,'mobile'=>$mobile]);
        return View::fetch("charge_check");

    }


    //客户充值提现
    public function charge($value=''){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/customer_login");

        $all=Request::param();

        $user = Db::table('user')->find($uid);
        if(!$user) return json_encode(['code'=>0,'msg'=>'User not found!']);

        if(empty($all['type'])) {
            json_encode(['code'=>0,'msg'=>'Invalid charge type!']);
        }

        $type=$all['type'];
        $type_name = $this->acc_type[$type];

        //提交充值操作
        if(!empty($all['money_charge'])){
            if(!is_numeric($all['money_charge'])){
                return json_encode(['code'=>0,'msg'=>'Invalid charge value!']);
            }
            if(empty($type)) {
                return json_encode(['code'=>0,'msg'=>'Invalid operation type!']);
            }

            $money = $all['money_charge'];
            //退款或提现
            if($type==2 || $type==4){
                $money = -$all['money_charge'];
            }

            $acc_log=array(
                'type'=>$type,
                'customer_id'=>$uid,
                'money'=>$money,
                'memo'=>$all['memo']?:'',
                'creater'=>2,
                'status'=>1,
                'create_time'=>date('Y-m-d H:i:s')
            );

            // if($type==4 && $user['money']<$all['money_charge']){
            //     return json_encode(['code'=>0,'msg'=>'余额不够 '.$acc_log['money'].',操作取消！']);
            // }

            $res =Db::table('acc_log')->insert($acc_log);
            if($res){
                return json_encode(['code'=>1,'msg'=>$type_name.'已提交，请耐心等待审核！']);
            }

            return json_encode(['code'=>0,'msg'=>'Unknow error!']);
        }

        $user['money']=number_format($user['money'],2);

        View::assign(['data'=>$user,'acc_type'=>$this->acc_type,'payment'=>$this->payment,'type'=>$type,'type_name'=>$type_name]);
        return View::fetch('charge_by_admin');
    }

    //账单查询——后台用
    public function acc_log(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login");

        $all=Request::param();

        if(!empty($all['cid'])){
          $cid =$all['cid'];
        }

        $view = 'acc_log';
        if(!empty($all['view'])) {
            $cid=$uid;
            $view.="_mobile"; 
        }
        $sdate= !empty($all['sdate'])?$all['sdate']:date('Y-m-d',time()-24*30*3600);
        
        $list=Db::table('acc_log');
        if(!empty($cid)) {
            $list =$list->where('customer_id',$cid);
        }

        //处理查询条件
        $list =$list->where('status',2)->order('create_time','desc')->where('create_time','>',$sdate);
        $list = $list->paginate(30)->toArray();

        foreach($list['data'] as &$log){
            $log['type_name']=$this->acc_type[$log['type']];
            $log['check_id_name']=$this->users[$log['check_id']]['name'];
            $log['money'] = number_format($log['money'],2);
            $log['customer_id_name'] = $this->users[$log['customer_id']]['name'];

        }

        $cid = !empty($all['cid'])?$all['cid']:'';
        View::assign(['list'=>$list,'cid'=>$cid]);
        return View::fetch($view);

    }


    //账单记录,app用
    public function fee_log(){
        $uid=Session::get('logonid');
        $all=Request::param(); 

        if(empty($uid) && empty($all['token'])) return header("location:/index.php/login");

        $list=Db::table('acc_log')->where('status','in','2,3');

        $cid='';
        $name='';

        if(!empty($all['token'])){
            $token =new token();
            $res = $token->check_token($all['token']);
            if($res['code']==0) return json($res);
            $cid = $res['customer']['id'];
        }

        $sdate = !empty($all['sdate'])?substr($all['sdate']." 00:00:00",0,20):'';
        $edate = !empty($all['edate'])?substr($all['edate']." 00:00:00",0,20):date('Y-m-d 23:59:59',time());
        if($edate<$sdate) return json('日期错误！');

        $type=(!empty($all['type']) && $all['type']>0) ?$all['type']:'1,2,3,4,5,6,7'; 
        $list->where('type','in',$type);

        if(!$cid && !empty($all['name'])){
            $name = trim($all['name']);
            $cid = Db::table('user')->where('name',$name)->value('id');
        }

        $mobile="";
        if(!$cid && !empty($all['mobile'])){
            $mobile = trim($all['mobile']);
            $cid = Db::table('user')->where('mobile',$mobile)->value('id');
        }

        if(!empty($cid)){
            $list->where('customer_id',$cid);
        }

        if(!empty($all['sdate'])){
            $list->where('create_time','>=',trim($sdate));
        }
        if(!empty($all['edate'])){
            $list->where('create_time','<=',trim($edate));
        }

        $sum = number_format($list->sum('money'),2);
        $count = number_format($list->count('id'),2);

        $list =$list->order('create_time','desc')->paginate(30)->toArray();
        foreach($list['data'] as &$log){
            $log['customer_id_name'] = $this->users[$log['customer_id']]['name'];
            $log['type_name']=$this->acc_type[$log['type']];
            $log['creater']=$this->users[$log['creater']]['name'];
            $log['check_by_name']=$this->users[$log['check_by']]['name'];

            $log['money'] = number_format($log['money'],2);
            $log['payment_name'] = $this->payment[$log['payment']];
            $log['status_name'] = $this->status[$log['status']];
        }

        
        if($type=='1,2,3,4,5,6,7') $type='all';

        View::assign([
            'list'=>$list,
            'acc_type'=>$this->acc_type,
            'name'=>$name,
            'mobile'=>$mobile,
            'type'=>$type,
            'sdate'=>$sdate,
            'edate'=>$edate,
            'count'=>$count,
            'sum'=>$sum
        ]);
        return View::fetch('fee_log');

    }  


    //账单记录
    public function fee_bi(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login");

        $all=Request::param(); 
        $sdate = !empty($all['sdate'])?$all['sdate']." 00:00:00":'';
        $edate = !empty($all['edate'])?$all['edate']." 23:59:59":date('Y-m-d 23:59:59',time());
        if($edate<$sdate) return json('日期错误！');
        $sql ="select dept_id,type,sum(money) as money from acc_log where 1 ";

        $dept_id = !empty($all['dept_id'])?$all['dept_id']:'all';
        if($dept_id!='all'){
            $sql .=" and  dept_id=".$all['dept_id'];
        }


        if(!empty($all['sdate'])){
            $sql .= " and create_time>='".trim($sdate)."'";
        }
        if(!empty($all['edate'])){
           $sql .= " and create_time<='".trim($edate)."'";
        }

        $sql.= " group by dept_id,type";

        //halt($sql);
        $list =Db::query($sql);

        //halt($list);

        foreach($list as &$log){
            $log['dept_id_name'] =$this->dept[$log['dept_id']]['name'];
            $log['type_name']=$this->acc_type[$log['type']];
            $log['money'] = round($log['money'],2);
        }

        $school = Db::table('dept')->where('status',1)->where('type',2)->select()->toArray();
        

        View::assign(['list'=>$list,'school'=>$school,'dept_id'=>$dept_id,'sdate'=>$sdate,'edate'=>$edate]);
        return View::fetch('fee_bi');

    }  



}
